<template>
  <div class="app-container">
    <SettlementAuditFilter
      :commSeleList="commSeleList"
      :commCaseSeleList="commCaseSeleList"
      @on-filter="submitFilterForm"
      @on-export="exportHandle"
      :downLoading="downloadLoading"
    />
    <div class="btn-group-view">
      <el-button
        v-if="roleCheck('batch-audit')"
        size="mini"
        type="primary"
        @click="multipAudit"
      >批量审核</el-button>
      <div class="rebate-mode">
        <span>结算返利模式:</span>
        <span>{{'人工审核'}}</span>
        <el-button
          size="mini"
          type="primary"
          @click="changeRebateMode"
        >修改</el-button>
      </div>
    </div>
    <el-table
      :data="tableData.list"
      border
      @selection-change="handleSelectionChange"
      v-loading="loading"
      element-loading-text="加载中..."
    >
      <el-table-column type="selection" :selectable="isSelectable" align="center" width="55"></el-table-column>
      <el-table-column prop="settleDate" label="结算周期" align="center" width="185"></el-table-column>
      <el-table-column label="代理账号" prop="username" align="center"></el-table-column>
      <el-table-column label="姓名" prop="name" align="center"></el-table-column>
      <el-table-column label="账号状态" align="center">
        <template slot-scope="{row}">
          <el-tag v-if="row.userStatus === 2" type="warning">间接锁定</el-tag>
          <el-tag v-else-if="row.userStatus === 3 " type="info">审核中</el-tag>
          <el-tag v-else-if="row.userStatus === 1 " type="danger">完全锁定</el-tag>
          <el-tag v-else-if="row.userStatus === -1|| row.userStatus === 0" type="success">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="会员代充额度" prop="amount" align="center">
        <template slot-scope="{row}">{{row.amount | currency}}</template>
      </el-table-column>
      <el-table-column label="代充返利" prop="amount" align="center">
        <template slot-scope="{row}">{{row.amount | currency}}</template>
      </el-table-column>
      <el-table-column label="累计未发放返利" prop="amount" align="center">
        <template slot-scope="{row}">{{row.amount | currency}}</template>
      </el-table-column>
      <el-table-column label="实际合计发放" prop="amount" align="center">
        <template slot-scope="{row}">{{row.amount | currency}}</template>
      </el-table-column>
      <el-table-column label="结算状态" fixed="right" prop="status" align="center" width="100">
        <template slot-scope="{row}">
          <div class="success">已结算</div>
          <el-button
            type="text"
            class="primary"
            @click="showAuditDialog(row,1)"
          >待审核</el-button>
          <el-button
            type="text"
            @click="showAuditDialog(row,2)"
          >未达标</el-button>
          <el-button
            type="text"
            class="danger"
            @click="showAuditDialog(row,2)"
          >已拒绝</el-button>
        </template>
      </el-table-column>
      <el-table-column label="时间" fixed="right" prop="firstTime" align="center" width="160">
        <template slot-scope="{row}">{{row.firstTime | toTime}}</template>
      </el-table-column>
      <el-table-column label="审核人" fixed="right" prop="firstApprover" align="center" width="100"></el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        background
        @size-change="gridSizeChange"
        @current-change="gridCurrentChange"
        :current-page="filters.page"
        :page-sizes="gridPageSize"
        :page-size="filters.size"
        :layout="gridLayout"
        :total="tableData.total"
      ></el-pagination>
    </div>
    <CommissionAuditDialog
      v-if="dialogName === staticDialogName"
      v-model="dialogVisible"
      :status="dialogProps.auditStatus"
      :id="dialogProps.id"
      :step="auditStep"
      @submit="submitFinished"
    />
    <CommissionAuditViewDialog
      v-if="dialogName === staticDialogName5"
      v-model="dialogVisible"
      :row-data="dialogProps"
      :step="auditStep"
      @submit="submitFinished"
    />
    <GameCommissionDialog
      v-if="dialogName === staticDialogName2"
      v-model="dialogVisible"
      :id="dialogProps.id"
      @submit="submitFinished"
    />

    <ApportionCommissionDialog
      v-if="dialogName === staticDialogName3"
      v-model="dialogVisible"
      :id="dialogProps.id"
      @submit="submitFinished"
    />

    <AdjustCommissionDialog
      v-if="dialogName === staticDialogName4"
      v-model="dialogVisible"
      :id="dialogProps.id"
      @submit="submitFinished"
    />
    <SubCommissionDialog
      v-if="dialogName === staticDialogName6"
      v-model="dialogVisible"
      :id="dialogProps.id"
      @submit="submitFinished"
    />
    <MultiplyAuditDialog
      v-if="dialogName === staticDialogName7"
      v-model="dialogVisible"
      :ids="idsArr"
      @submit="submitFinished"
    />
    <NextMemberCommissionDialog
      v-if="dialogName === staticDialogName8"
      v-model="dialogVisible"
      :detail="dialogProps"
    />
    <AddPointsRebate
      v-if="dialogName === staticDialogName9"
      v-model="dialogVisible"
      :detail="dialogProps"
    />
    <ChangeRebateMode
      v-if="dialogName === staticDialogName10"
      v-model="dialogVisible"
      :detail="dialogProps"
    />
  </div>
</template>

<script>

// constants
import agencyEnum, { FILTER_ALL_TYPE } from '@/const/agencyEnum';

// utils
import { formatCommMode, mapToArray } from '@/utils/base';

// components
import SettlementAuditFilter from './auditFilter';
import CommissionAuditDialog from './auditDialog';
import GameCommissionDialog from './gameCommissionDialog';
import ApportionCommissionDialog from './apportionCommissionDialog';
import AdjustCommissionDialog from './adjustCommissionDialog';
import CommissionAuditViewDialog from './auditViewDialog';
import SubCommissionDialog from './subCommissionDialog';
import MultiplyAuditDialog from './multiplyAuditDialog';
import NextMemberCommissionDialog from './nextMemberCommissionDialog';
import AddPointsRebate from './addPointsRebate';
import ChangeRebateMode from './changeRebateMode';

// service
import {
  getCommissionAudits,
  getCommissionSelect,
  getCommissionCaseSelectList,
} from '@/services/api/commission';

// mixins
import { grid, dialog } from '@/build';

const headerMap = {
  settleDate: '结算周期',
  username: '代理账号',
  name: '姓名',
  userStatus: '账号状态',
  userCount: '有效会员',
  proxyCount: '有效下级代理总数',
  formatWinTotal: '公司总输赢',
  formatCost: '成本总计',
  formatLastAmount: '累加上月',
  formatCommAmount: '下级会员佣金',
  formatProxyComm: '下级代理佣金',
  formatAmount: '实际合计发放',
  status: '结算状态',
  firstTime: '时间',
  firstApprover: '审核人',
};

export default {
  name: 'commission-settlement-audit',
  components: {
    CommissionAuditViewDialog,
    AdjustCommissionDialog,
    SubCommissionDialog,
    NextMemberCommissionDialog,
    ApportionCommissionDialog,
    GameCommissionDialog,
    CommissionAuditDialog,
    SettlementAuditFilter,
    MultiplyAuditDialog,
    AddPointsRebate,
    ChangeRebateMode,
  },
  mixins: [grid, dialog],
  data() {
    return {
      tableData: {},
      ids: [],
      filters: {
        size: 20,
        page: 1,
        searchType: 1,
        settleDate: moment().format('YYYY-MM'),
      },
      auditStep: 0,
      dialogVisible: false,
      staticDialogName: 'commission-audit-dialog',
      staticDialogName2: 'game-commission-dialog',
      staticDialogName3: 'apportion-commission-dialog',
      staticDialogName4: 'adjust-commission-dialog',
      staticDialogName5: 'commission-audit-view-dialog',
      staticDialogName6: 'sub-commission-dialogg',
      staticDialogName7: 'mul-commission-audit-dialog',
      staticDialogName8: 'next-member-commission-dialog',
      staticDialogName9: 'add-points-rebate',
      staticDialogName10: 'change-rebate-mode',
      commSeleList: [],
      commCaseSeleList: [],
    };
  },
  computed: {
    idsArr() {
      return this.ids.map(item => item.id);
    },
  },
  methods: {
    changeRebateMode(row) {
      this.openDialog({ props: row, dialogName: this.staticDialogName10 });
    },
    formatCommMode,
    formatFeeRuleName(row) {
      if (!this.commSeleList.length) return null;
      const { name } = this.commSeleList.find(item => item.id === row.feeRule) || {};
      return name;
    },
    formatCashRuleName(row) {
      if (!this.commCaseSeleList.length) return null;
      const { name } = this.commCaseSeleList.find(item => item.id === row.cashRule) || {};
      return name;
    },
    isSelectable(row) {
      return !_.includes([2, 3, 4], row.status);
    },
    showAuditDialog(row, step) {
      this.auditStep = step;
      // 初审备注
      this.firstRemark = row.firstRemark;
      this.openDialog({ props: row, dialogName: this.staticDialogName });
    },
    submitFilterForm(formInline) {
      this.formatData(formInline);
      this.gridSearch();
    },
    // 表格前面的checkbox操作
    handleSelectionChange(val) {
      this.ids = val;
    },
    multipAudit() {
      if (this.idsArr.length <= 0) {
        this.$message({
          type: 'warning',
          message: '请勾选数据',
        });
        return;
      }
      this.openDialog({ dialogName: this.staticDialogName7 });
    },
    setStep(step) {
      this.auditStep = step;
    },
    // 导出
    async exportHandle(formInline) {
      try {
        this.downloadLoading = true;
        this.formatData(formInline);
        const [status, result] = await getCommissionAudits(this.filters);
        if (!status) throw new Error(result.message);
        const filename = '佣金结算报表.csv';
        const header = mapToArray(headerMap);
        const filterField = Object.keys(headerMap);
        const exportData = this.formatList(result.list);
        this.export2Excel(header, filterField, exportData, filename);
      } catch (e) {
        this.$message({
          message: `${e.message || ''}`,
          type: 'error',
        });
      } finally {
        this.downloadLoading = false;
      }
    },
    formatList(list) {
      return list.map(item => ({
        ...item,
        formatFeeRule: this.formatFeeRuleName(item),
        formatCommName: this.formatCommMode(item.commMode).name,
        formatCashRule: item.commMode === 1 ? this.formatCashRuleName(item) : '--',
        formatWinTotal: _.currency(item.winTotal),
        formatCost: _.currency(item.cost),
        formatLastAmount: _.currency(item.lastAmount),
        formatCommAmount: _.currency(item.commAmount),
        formatProxyComm: _.currency(item.proxyComm),
        formatUpAmountRet: _.currency(item.upAmountRet),
        formatAmount: _.currency(item.amount),
        status: agencyEnum.AUDIT_REVIEW_TYPE[item.status],
        userStatus: agencyEnum.COMMISSION_ACCOUNT_STATUS[item.userStatus],
        firstTime: _.toTime(item.firstTime),
      }));
    },
    formatData(formInline) {
      this.filters = { ...this.filters, ...formInline };
    },
  },
  mounted() {
    this.bindGet(getCommissionSelect, 'commSeleList', {
      format: (data) => {
        if (!(Array.isArray(data) && data.length)) return [];
        data.unshift(FILTER_ALL_TYPE);
        return data;
      },
    });
    this.bindGet(getCommissionCaseSelectList, 'commCaseSeleList', {
      format: (data) => {
        if (!(Array.isArray(data) && data.length)) return [];
        data.unshift(FILTER_ALL_TYPE);
        return data;
      },
    });
    this.bindGet(getCommissionAudits, 'tableData', {
      action: 'getGrid',
      sendingData: 'filters',
    });
    this.getAll();
  },
};
</script>

<style lang="scss" scoped>
.success {
  color: #67C23A;
}

.primary {
  color: #409EFF;
}

.danger {
  color: #F56C6C;
}

.btn-group-view {
  padding: 20px 0;
  display: flex;

  .rebate-mode {
    display: flex;
    font-size: 14px;
    align-items: center;
    padding-left: 50px;

    .el-button {
      margin-left: 10px;
    }
  }
}
</style>
